package com.example.sys.job.service;

import com.example.core.utils.SpringBeanUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Map;


/***
 *
 * 用户服务代理定时任务执行类
 */
public class SysUserJobProxy implements Job {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        ApplicationContext applicationContext = SpringBeanUtils.getApplicationContext();
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        if (jobDataMap.containsKey(SysJobService.MODELID) && jobDataMap.containsKey(SysJobService.MODELNAME)) {
            String modelId = jobDataMap.getString(SysJobService.MODELID);
            String modelName = jobDataMap.getString(SysJobService.MODELNAME);
            Map<String, SysJobRunTimeService> serviceMap = applicationContext.getBeansOfType(SysJobRunTimeService.class);
            for (SysJobRunTimeService sysJobRunTimeService : serviceMap.values()) {
                sysJobRunTimeService.execute(modelName, modelId);
            }
            //用户任务执行后，自动删除不再留痕.
            try {
                applicationContext.getBean(SysJobService.class).deleteUserJob(modelId);
            } catch (Exception e) {
                logger.warn("清理用户任务失败: " + e.getMessage());
            }
        }
    }
}
